package 线程通信.信标法;

import javax.swing.*;

/*
生产者与消费者的关系---》观看节目
相对于就是设置一个标记位，通过不同的状态来控制进程的交替执行
 */
public class test {
    public static void main(String[] args) {
        show show = new show();
        producers producers = new producers(show);
        consumers consumers = new consumers(show);

        new Thread(producers).start();
        new Thread(consumers).start();


    }
}

//生产节目
class producers implements Runnable {
    private show show;

    public producers() {
    }

    public producers(show show) {
        this.show = show;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
//            System.out.println(i);
            if (i % 2 == 0) {
                show.producersShow("快乐" + i);
            } else {
                show.producersShow("不快乐快乐" + i);
            }
        }
    }
}

//消费者
class consumers implements Runnable {
    private show show;

    public consumers() {
    }

    public consumers(show show) {
        this.show = show;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            show.pop();
        }
    }
}

//节目
class show {
    private String voice;//节目
    private static Boolean tag = false;//标志位

    //生成节目
    public synchronized void producersShow(String voice) {
        if (tag) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("演员表演了" + voice);
        this.voice = voice;
        this.tag = true;
        this.notify();//通知观众观看
    }

    //观看节目
    public synchronized void pop() {
        if (!tag) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.println("观看了节目" + voice);
        this.tag = false;
        this.notify();
    }

}
